package framework

import (
	"ReferenceMonitor/sdk/rpc/service_manager"
	"fmt"
	"log"
)

type DMServiceAPI struct {
	*service_manager.ServiceManager
	devClients  map[string]*service_manager.ClientRPC
	curClientIP string // 当前cli中选择的client
}

func NewDMSApi() *DMServiceAPI {
	return &DMServiceAPI{
		devClients: make(map[string]*service_manager.ClientRPC),
	}
}

func (dm *DMServiceAPI) Start(ip string, ty string) {
	dm.ServiceManager = service_manager.InitDMService(ip, ty)
	dm.StartRPCServer()
	go dm.onLog()
}

func (dm *DMServiceAPI) ConnectDevice(ip string) bool {
	var client *service_manager.ClientRPC
	if _, ok := dm.devClients[ip]; !ok {
		client = service_manager.NewClientRPC(ip, &dm.DM.CurDv)
		dm.devClients[ip] = client
		if client == nil {
			fmt.Println("Failed to ConnectDevice: ", ip)
			return false
		}
	}
	client = dm.devClients[ip]
	dev, err := client.FindDevice()
	if err != nil {
		return false
	}
	dev.DevAddr = ip
	dm.DM.DeviceMap[dev.Tag] = &dev
	dm.curClientIP = ip
	return true
}

func (dm *DMServiceAPI) VerifyDevice(code string) bool {
	fmt.Println(dm.devClients)
	if client, ok := dm.devClients[dm.curClientIP]; ok {
		yes, msg := client.VerifyDevice(code)
		if !yes {
			fmt.Println(msg)
			return false
		}
		dm.DM.CurDv.Status = service_manager.STATUS_VERIFIED
		return true
	}
	fmt.Println("CurrentDev is Not Exist: ", dm.curClientIP)
	return false
}

func (dm *DMServiceAPI) onLog() {
	for {
		select {
		case m := <-dm.ServiceManager.LogQueue:
			log.Println(m)
		}
	}
}

func (dm *DMServiceAPI) StopService() {
	dm.ServiceManager.Stop()
}

type DMClientAPI struct {
}
